package com.dudu.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dudu.bean.AccountBean;
import com.dudu.bean.AppExtendBean;
import com.dudu.bean.ChargingRuleBean;
import com.dudu.bean.PoolAbilityInfoBean;
import com.dudu.bean.PoolCaseBean;
import com.dudu.service.IAccountExtendService;
import com.dudu.service.IAppExtendService;
import com.dudu.service.ICheckValidityService;
import com.dudu.service.ILogService;
import com.dudu.service.IPoolNumberUtilsService;
import com.dudu.service.IRuleService;
import com.dudu.service.impl.AccountExtendServiceImpl;
import com.dudu.service.impl.AppExtendServiceImpl;
import com.dudu.service.impl.CheckValidityServiceImpl;
import com.dudu.service.impl.LogService;
import com.dudu.service.impl.PoolNumberUtilsServiceImpl;
import com.dudu.service.impl.RuleServiceImpl;
import com.dudu.utils.DateUtils;

import core.CoreService;

/**
 * 号码池信息查询接口
 * 
 * @author 危东
 * @date 2016年6月3日
 * 
 */
public class OpenPoolNumberController extends CoreService implements IOpenPoolNumberController {
    // 用于记录相应接口调用的日志
    private ILogService logService = new LogService();

    // app扩展信息操作
    private IAppExtendService appExtendService = new AppExtendServiceImpl();
    private IAccountExtendService accountExtendService = new AccountExtendServiceImpl();
    // 验证信息类
    private ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
    // 查询号码配置信息类
    private IPoolNumberUtilsService poolNumberUtilsService = new PoolNumberUtilsServiceImpl();
    private IRuleService ruleService = new RuleServiceImpl();

    /**
     * 根据账号标识、应用标识和能力类型查询号码信息
     * 
     * @return
     */
    @Override
    public String qryAccNumInfoList() {
	log.info("load OpenPoolNumberController.qryAccNumInfoList 根据账号标识和应用标识查询号码和号码开通的能力信息 ");
	// 计算接口调用开始时间
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 能力类型abilityType
	String ability_type = this.getRequest().getParameter("ability_type");
	String[] ability_typeStr = { "ability_type", ability_type, "50", "1", "str" };
	checkParamlist.add(ability_typeStr);
	// 父能力类型
	String parent_ability_type = this.getRequest().getParameter("parent_ability_type");
	String[] parent_ability_typeStr = { "parent_ability_type", parent_ability_type, "10", "1", "str" };
	checkParamlist.add(parent_ability_typeStr);
	// 号码类型（1:平台号；2：用户认证号；空值全部号码）
	String numberType = this.getRequest().getParameter("number_type");
	String[] numberTypeStr = { "numberType", numberType, "5", "1", "str" };
	checkParamlist.add(numberTypeStr);
	if (StringUtils.isBlank(numberType)) {
	    numberType = "2"; // 默认查询用户认证号码
	}

	// 对外返回的参数值
	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		// 查询应用信息
		AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		// 判断app信息是否为空
		if (appExtendBean != null) {
		    // 根据cust_account查询账号信息
		    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
		    // 判断账号信息是否找到
		    if (accountBean != null) {
			// 验证秘钥信息
			if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
			    // 使用能力自带类型
			    if (StringUtils.isNotBlank(parent_ability_type)) {
				ChargingRuleBean chargingRule = ruleService.queryChargingRule(appExtendBean.getApp_key(), accountBean.getCust_account(), parent_ability_type);
				if (chargingRule != null) {
				    ability_type = chargingRule.getType();
				}
			    }
			    // 查询账号和相应能力所配置的显号
			    List<PoolAbilityInfoBean> listPools = poolNumberUtilsService.getPoolNumberInfoList(getDao(), app_key, cust_account, ability_type, null, numberType,
				    null);
			    if (listPools != null) {
				if (!listPools.isEmpty() && listPools.size() > 0) {
				    // 用于最终返回值
				    JSONArray dataArray = new JSONArray();
				    // 遍历查询出来的号码
				    for (int i = 0; i < listPools.size(); i++) {
					// 获取相应实体类
					PoolAbilityInfoBean poolAbilityInfoBean = listPools.get(i);
					// 拼写返回值信息
					JSONObject objectInfo = new JSONObject();
					// 能力类型
					objectInfo.put("pool_ability_id", poolAbilityInfoBean.getId() + "");
					// 能力类型
					objectInfo.put("ability_type", poolAbilityInfoBean.getAbility_type());
					// 计费账号
					objectInfo.put("charge_number", poolAbilityInfoBean.getCharge_number());
					// 显示号码
					objectInfo.put("display_number", poolAbilityInfoBean.getDisplay_number());
					// 限制个数
					objectInfo.put("limit_num", poolAbilityInfoBean.getLimit_num());
					// 将数据写入
					dataArray.add(objectInfo);
				    }
				    object.put("result", "0");
				    object.put("describe", "查询成功");
				    object.put("code", "0000");
				    object.put("data", dataArray.toString());
				} else {
				    object.put("result", "0");
				    object.put("describe", "未配置相应号码");
				    object.put("code", "0000");
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "未查询到相应号码配置");
				object.put("code", "0007");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "参数sign错误");
			    object.put("code", "0001");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "未找到相应账号信息！");
			object.put("code", "0100");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "请使用正确的应用标识");
		    object.put("code", "0007");
		}
	    }
	} catch (Exception e) {
	    log.info("查询失败");
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "错误");
	}
	// 接口调用结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "app_key:" + app_key + "|cust_account:" + cust_account + "|timestamp:" + timestamp + "|sign:" + sign + "|ability_type" + ability_type;
	this.logService.logInterface(during, "qryAccPoolV4", request_msg, object.toString().length() > 1990 ? object.toString().substring(0, 1990) : object.toString(),
		object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), "");

	return returnData(object.toString());
    }

    /**
     * 根据账号标识、应用标识和能力类型，查询某一天的某个号码的使用量
     * 
     * @return
     */
    @Override
    public String qryAccNumTimes() {
	log.info("load OpenPoolNumberController.qryAccNumTimes 根据账号标识和应用标识，查询某一天的某个号码的使用量 ");
	// 计算接口调用开始时间
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 查询的日期，如：2016-06-13
	String qre_date = this.getRequest().getParameter("qre_date");
	String[] qre_dateStr = { "qre_date", qre_date, "20", "0", "str" };
	checkParamlist.add(qre_dateStr);
	// 能力id
	String pool_ability_id = this.getRequest().getParameter("pool_ability_id");
	String[] pool_ability_idStr = { "pool_ability_id", pool_ability_id, "20", "1", "str" };
	checkParamlist.add(pool_ability_idStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 对外返回的参数值
	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		// 查询应用信息
		AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		// 判断app信息是否为空
		if (appExtendBean != null) {
		    // 根据cust_account查询账号信息
		    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
		    // 判断账号信息是否找到
		    if (accountBean != null) {
			// 验证秘钥信息
			if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
			    // 查询相应能力，查询一天的使用量
			    List<PoolCaseBean> poolCaseList = poolNumberUtilsService.queryNumTimeByDate(getDao(), app_key, cust_account, pool_ability_id, qre_date);
			    // 返回的data值
			    JSONObject dataObject = new JSONObject();
			    if (poolCaseList != null) {
				// 遍历值
				for (int i = 0; i < poolCaseList.size(); i++) {
				    // 获取相应值
				    PoolCaseBean poolCaseBeanTemp = poolCaseList.get(i);
				    dataObject.put(poolCaseBeanTemp.getPool_ability_id() + "", poolCaseBeanTemp.getNum_time());
				}
				object.put("result", "0");
				object.put("describe", "查询成功");
				object.put("code", "0000");
				object.put("data", dataObject.toString());
			    } else {
				object.put("result", "-1");
				object.put("describe", "未查询到相应信息");
				object.put("code", "0001");
				object.put("data", "");
			    }

			} else {
			    object.put("result", "-1");
			    object.put("describe", "参数sign错误");
			    object.put("code", "0001");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "未找到相应账号信息！");
			object.put("code", "0100");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "请使用正确的应用标识");
		    object.put("code", "0007");
		}
	    }
	} catch (Exception e) {
	    log.info("查询失败");
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "错误");
	}
	// 接口调用结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "app_key:" + app_key + "|cust_account:" + cust_account + "|timestamp:" + timestamp + "|sign:" + sign + "|qre_date" + qre_date + "|pool_ability_id"
		+ pool_ability_id;
	this.logService.logInterface(during, "qryAccPoolTimesV4", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), this.getRequest()
		.getRemoteAddr(), "");

	return returnData(object.toString());
    }

}
